package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.domain.dto.QueryData;
import com.ruoyi.project.system.domain.vo.*;
import com.ruoyi.project.system.domain.vo.BaseReport;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.BdReportService;
import com.ruoyi.project.system.service.TencentService;
import com.ruoyi.project.system.service.TzBeiDiaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.text.Convert.toStr;
import static com.ruoyi.common.utils.CardNoUtils.getBirAgeSex;
import static com.ruoyi.common.utils.DateUtils.dateTime;
import static com.ruoyi.common.utils.http.HttpUtils.sendPost;
import static com.ruoyi.common.utils.uuid.Seq.getId;

@Service
public class TzBeiDiaoServiceImpl implements TzBeiDiaoService {

    @Autowired
    private TencentService tencentService;

    @Autowired
    private BdReportService bdReportService;

    @Autowired
    private TzBeiDiaoMapper tbdm;

    @Autowired
    private SiyuUserPriceMapper supm;

    @Autowired
    private SiyuBlacklistMapper sbm;

    @Autowired
    private SiyuChargeMapper scm;

    @Override
    public List<ProductPriceVo> beiDiaoProduct(List<ProductEnable> pes, Long userId) {
        List<Integer> allProductId = pes.stream().map(ProductEnable::getId).collect(Collectors.toList());
        List<SiyuUserPrice> userPrices = supm.selectPricesByIds(allProductId, userId);
        List<Integer> partProductId = userPrices.stream().map(SiyuUserPrice::getProductId).collect(Collectors.toList());

        List<ProductPriceVo> productPriceVos = new ArrayList<>();
        for (int i = 0; i < allProductId.size(); i++) {
            int index = partProductId.indexOf(allProductId.get(i));
            if (index == -1) {
                productPriceVos.add(new ProductPriceVo(pes.get(i)));
            } else {
                productPriceVos.add(new ProductPriceVo(pes.get(i), userPrices.get(index)));
            }
        }
        return productPriceVos;
    }

    @Override
    public AuthelecDto handlerFaceAuth(FaceBackResultVo fbrv) throws Exception {
        String orderNo = tbdm.selectAuthelecByOrderNo(fbrv.getOrderNo());
        if (StringUtils.isEmpty(orderNo)) {
            tbdm.insertAuthelec(new AuthelecDto(fbrv));
        } else {
            tbdm.updateAuthelec(new AuthelecDto(fbrv));
        }
        int i = 1;
        AuthelecDto authelecDto;
        String authResult;
        do {

            JSONObject faceAuth = tencentService.getFaceAuthResult(fbrv.getOrderNo());
            if ("0".equals(faceAuth.getString("code")) && faceAuth.containsKey("result")) {
                authelecDto = new AuthelecDto(faceAuth);
                authResult = "已人脸授权";
                break;
            } else {
                authelecDto = new AuthelecDto(fbrv.getOrderNo(), faceAuth.getString("msg"));
                Thread.sleep(2000);
                authResult = "授权失败";
            }
        } while (i++ < 2);
        tbdm.updateBeiDiao(new BeiDiaoBase(fbrv.getOrderNo(), authResult));
        tbdm.updateAuthelec(authelecDto);
        return authelecDto;
    }

    @Override
    public Map<String, Object> queryReport(SiyuCharge sc) {
        Integer productId = sc.getProductId().intValue();
        BeiDiaoBase bdb = tbdm.selectBeiDiaoById(sc.getQueryId());

        Map<String, Object> resultInfo = new HashMap<>();
        resultInfo.put("orderNo", bdb.getOrderNo());
        resultInfo.put("productId", productId);
        resultInfo.put("queryTime", dateTime(sc.getCreateTime()));
        if (productId == 20) {
            resultInfo.putAll(bdReportService.fast(bdb));
        } else if (productId == 21) {
            resultInfo.putAll(bdReportService.ordinary(bdb));
        } else if (productId == 22) {
            resultInfo.putAll(bdReportService.onboardingSurvey(bdb));
        }
        return resultInfo;
    }

    @Override
    public Report queryReportHead(BeiDiaoVo bdv) {
        Long userId = SecurityUtils.getUserId();
        BaseReport bp = tbdm.selectBeiDiaoBaseReportByOrderNo(bdv.getOrderNo());
        if (bp == null) {
            bp = new BaseReport(bdv.getOrderNo());
            String baseReqSn = "TQ" + getId();
            JSONObject ncParams = new JSONObject();
            ncParams.put("name", bdv.getName());
            ncParams.put("cardNo", bdv.getIdNumber());

            JSONObject ncmParams = new JSONObject();
            ncmParams.putAll(ncParams);
            ncmParams.put("mobile", bdv.getTel());

            // 1 手机号在网时长
            BaseReport finalBp = bp;
            CompletableFuture<Void> zwsc = CompletableFuture.runAsync(() -> {
                JSONObject mParams = new JSONObject();
                mParams.put("mobile", bdv.getTel());
                mParams.put("inter_id", "JF030");
                mParams.put("request_sn", baseReqSn + "JF030");
                QueryData qd = sendPost(mParams);
                if (qd.isSuccess()) {
                    JSONObject retdata = (JSONObject) qd.getInfo();
                    finalBp.setOnlineTime(retdata.getString("inTime"));
                } else {
                    finalBp.setOnlineTime(qd.getMsg());
                }
            });

            // 2 二要素核验
            CompletableFuture<Void> eyshy = CompletableFuture.runAsync(() -> {
                ncParams.put("inter_id", "JF061");
                ncParams.put("request_sn", baseReqSn + "JF061");
                QueryData qd = sendPost(ncParams);
                if (qd.isSuccess()) {
                    JSONObject retdata = (JSONObject) qd.getInfo();
                    String status = retdata.getString("status");
                    finalBp.setTwoEleCheck("1".equals(status) ? "通过" : "未通过");
                } else {
                    finalBp.setTwoEleCheck(qd.getMsg());
                }
            });

            // 3 三要素核验
            CompletableFuture<Void> syshy = CompletableFuture.runAsync(() -> {
                ncmParams.put("inter_id", "JF007");
                ncmParams.put("request_sn", baseReqSn + "JF007");
                QueryData qd = sendPost(ncmParams);
                if (qd.isSuccess()) {
                    JSONObject retdata = (JSONObject) qd.getInfo();
                    finalBp.setTelLocal(toStr(retdata.getString("province"), "") + toStr(retdata.getString("city"), ""));
                    finalBp.setCarrier(toStr(retdata.getString("attribute"), ""));
                    String cr = retdata.getString("checkResult");
                    finalBp.setThrEleCheck("0".equals(cr) ? "通过" : "未通过");
                }
            });
            CompletableFuture<Void> all = CompletableFuture.allOf(zwsc, eyshy, syshy);

            System.out.println(System.currentTimeMillis() + ":阻塞");
            all.join();
            all.thenAccept(result -> {
                System.out.println("Task 2 is executed with input: " + finalBp);
                tbdm.insertBaseReport(finalBp);
            });
            System.out.println(System.currentTimeMillis() + ":阻塞结束");
        }
        Report report = new Report(bp, bdv);
        String idNumber = bdv.getIdNumber();
        Map<String, String> birAgeSex = getBirAgeSex(idNumber);
        report.setSex(birAgeSex.get("sex"));
        report.setAge(birAgeSex.get("age"));
        report.setBlackList(sbm.selectBlackList(new SiyuBlacklist(bdv)) != null);
        List<ReportProductRecord> rprs = scm.reportFeeRecord(bdv);
        for (ReportProductRecord rpr : rprs) {
            SiyuUserPrice sup = supm.selectPriceByUIAadPI(userId, rpr.getProductId());
            if (sup != null) {
                rpr.setPrice(sup.getPrice());
            }
        }
        report.setRpp(rprs);
        return report;
    }
}
